﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Anthem;
using spUtils;
using spMapping;
using spData.Common;
using spWeb;

namespace demo.Page.XZ
{
    public partial class xz_Flswsqd : TaskPage
    {
        #region Property
        //初始化下拉
        DDLBind db = new DDLBind();
        #endregion

        #region Method Init Controls Value & Show/Hide & Enable/Disable & Opinion
        private void InitControls()
        {
            #region Init controls value
            //绑定城市
            db.BindCity(City);

            Expression exp = new Expression();
            string did = Request.QueryString["DID"];
            exp = string.IsNullOrEmpty(did) ? dc_xz_Flswsqd.process == TaskAPI.Process & dc_xz_Flswsqd.incident == TaskAPI.Incident : dc_xz_Flswsqd.id == did;
            if (TaskAPI.IsInitiate)
            {
                exp &= dc_xz_Flswsqd.userName == USER.UserName;
            }

            dc_xz_Flswsqd v = exp.ListFirst<dc_xz_Flswsqd>();
            if (v != null)
            {
                SetControlsValue(v);
                DepEName.Text = v.Department;
                //DID方式加载
                if (!string.IsNullOrEmpty(did))
                {
                    TaskAPI.LoadByDID(v.Process, v.Incident);
                    Process = v.Process;
                    Incident = v.Incident;
                }
                Kcry.Attributes["onclick"] = string.Format("OpenDialog2('../../Workflow/spMulEmployee.aspx?v=1&ep={0}','840','560','v',this.id,'1')", KcryUser.Text.Replace(";", ","));
            }
            else
            {
                UserFullName.Text = USER.UserFullName;
                Time.Text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                Department.Text = USER.Department;
                DepEName.Text = USER.DepEName;
                Tel.Text = USER.EXTEND.CellPhone;
            }
            #endregion

            #region Init Show/Hide、Enable/Disable
            bool flg = TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit;
            SetEnable(flg, City, Gsgs, Xmmc, Bt, Sqnr, Flswgk, Flswqq, Yclgk, Jyclfa, Nwtdlr, Dlqx, Xbr, Bzsm);
            SetVisible(flg, R_Csgs, R_Gsgs, R_Xmmc, R_Bt, R_Sqnr, R_Flswgk, R_Flswqq, R_Yclgk, R_Jyclfa, R_Nwtdlr, R_Dlqx, R_Xbr, R_Bzsm);
            #endregion
        }
        #endregion

        #region Method Data Validation
        private List<string> DataValidation()
        {
            List<Regular> regs = new List<Regular>();
            if (!AssExt.IsConferWithBack && !AssExt.IsForwardWithBack)
            {
                if (TaskAPI.IsBeginStep)
                {
                    regs.Add(new Regular(RegularExp.NotEmpty, City.Text, "“城市公司”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Gsgs.Text, "“开发公司”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Xmmc.Text, "“项目名称”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Bt.Text, "“标题”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Sqnr.Text, "“申请内容”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Flswgk.Text, "“法律事务概况”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Flswqq.Text, "“法律事务请求”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Yclgk.Text, "“已经处理概况”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Jyclfa.Text, "“建议处理方案”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Nwtdlr.Text, "“拟委托代理人”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Dlqx.Text, "“代理权限”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Xbr.Text, "“协办人”为必填项!"));
                    regs.Add(new Regular(RegularExp.NotEmpty, Bzsm.Text, "“建议处理方案”为必填项!"));
                }


            }
            return Validation(regs);
        }
        #endregion

        #region Method Engine Transfer Value
        private void EngineTransferValue()
        {
            if (TaskAPI.IsBeginStep)
            {
                TaskAPI.Summary = Xmmc.Text;
                WebHelper.IntSetValue(this.TaskAPI, Gsgs.SelectedValue, Xmmc.SelectedValue);
            }

            if (TaskAPI.Step == "依次会签")
            {
                object[] s;

                //顺序调整
                if (TaskAPI.IsBeginStep)
                {
                    object[] tmps = KcryUser.Text.Replace("'", "").Replace("xckg/,", ",").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    s = new object[tmps.Length];
                    int kk = 0;
                    for (int k = 0; k < tmps.Length; k++)
                    {
                        if (tmps[k] == null || string.IsNullOrEmpty(tmps[k].ToString()) || tmps[k].ToString() == "xckg/")
                        {
                            continue;
                        }

                        s[kk] = tmps[k].ToString().Contains("xckg/") ? tmps[k] : string.Format("xckg/{0}", tmps[k]);
                        kk++;
                    }

                }
                else
                {
                    s = TaskAPI["r_Ychq"] as object[];
                }

                if (s != null)
                {
                    bool flg = true;
                    for (int i = 0; i < s.Length; i++)
                    {
                        if (s[i] != null && !string.IsNullOrEmpty(s[i].ToString())
                            && AssExt.Assessment.Opinion != "2"
                            && AssExt.Assessment.Opinion != "3")
                        {
                            TaskAPI["r_Ychq_use"] = s[i].ToString();
                            s[i] = "";
                            flg = false;
                            break;
                        }
                    }

                    //如果已经是最后一个人员审批的情况
                    if (flg && AssExt.Assessment.Opinion != "2"
                            && AssExt.Assessment.Opinion != "3")
                    {
                        TaskAPI["r_Ychq_use"] = "NA";
                    }

                    if (!flg && AssExt.Assessment.Opinion != "2" && AssExt.Assessment.Opinion != "3")
                    {
                        //将数据转移至新的数组
                        int loc = 0;
                        string[] s2 = new string[s.Length];
                        for (int i = 0; i < s.Length; i++)
                        {
                            if (s[i] != null && !string.IsNullOrEmpty(s[i].ToString()))
                            {
                                s2[loc] = s[i].ToString();
                                loc++;
                            }
                        }
                        TaskAPI["r_Ychq"] = s2;
                    }
                }
            }
            TaskAPI["e_Approve"] = AssExt.Assessment.Opinion;
        }

        #endregion

        #region Method Submit
        private bool Submit(bool IsSend)
        {
            #region “开始”步骤
            if (TaskAPI.IsBeginStep)
            {
                dc_xz_Flswsqd v = (dc_xz_Flswsqd.process == TaskAPI.Process & dc_xz_Flswsqd.incident == TaskAPI.Incident
                                & dc_xz_Flswsqd.userName == (TaskAPI.IsInitiate ? USER.UserName : TaskAPI.UserName)).ListFirst<dc_xz_Flswsqd>();
                bool result = GetControlsValue<dc_xz_Flswsqd>(ref v);
                if (result)
                {
                    v.Process = TaskAPI.Process;
                    v.Incident = TaskAPI.Incident;
                    v.UserName = USER.UserName;
                    v.UserFullName = USER.UserFullName;
                    v.Time = System.DateTime.Now;
                    ApplicationNo.Text = GetNewSequence("KCG-CGLXD-" + DateTime.Now.ToString("yyyyMMdd") + "-", "", 3);
                    v.ApplicationNo = ApplicationNo.Text;
                }
                ORM.Save(v);
            }
            #endregion

            #region 依次会签
            if (TaskAPI.Step == "依次会签")
            {
                try
                {
                    object[] s = (object[])(TaskAPI["r_Ychq_use"]);
                    t_Tasks task = (t_Tasks.processName == TaskAPI.Process & t_Tasks.incident == TaskAPI.Incident & t_Tasks.stepLabel == "填写申请单").ListFirst<t_Tasks>(ORM.Context2);
                    if (task != null && s != null
                        && s[0] != null && !string.Equals(s[0], @"NA"))
                    {
                        t_ConferTo confer = new t_ConferTo();
                        confer.UserName = USER.UserName;
                        confer.AssignedToUserName = USER.UserName;
                        confer.Process = Process;
                        confer.Incident = Incident;
                        confer.Step = Step;
                        confer.Category = "FORWARD";
                        confer.Time = System.DateTime.Now;
                        confer.Status = 2;
                        confer.TaskID = task.TaskID.Trim();
                        ORM.Save(ORM.Context2, confer);
                    }
                }
                catch (Exception)
                {
                }
            }
            #endregion

            if (!TaskAPI.IsInitiate && (AssExt.Assessment.Opinion != "1"))
            {
                t_Tasks task = (t_Tasks.processName == Process & t_Tasks.stepLabel != TaskAPI.GoToStep & t_Tasks.incident == Incident).ListFirst<t_Tasks>(ORM.Context2, t_Tasks.endTime.Desc);
                if (task != null)
                {
                    (t_ConferTo.process == Process & t_ConferTo.process.IsNotNull() & t_ConferTo.process != ""
                   & t_ConferTo.incident == Incident & t_ConferTo.incident.IsNotNull()).Edit<t_ConferTo>(ORM.Context2, o => o.TaskID = task.TaskID.Trim());
                }
            }


            if (IsSend)
            {
                EngineTransferValue();
                ORM.Save(AssExt.Assessment);
                TaskAPI.Send();
            }

            if (IsSend && TaskAPI.IsInitiate)
            {
                (dc_xz_Flswsqd.process == TaskAPI.Process & dc_xz_Flswsqd.incident == 0 & dc_xz_Flswsqd.userName == USER.UserName).Edit<dc_xz_Flswsqd>(p =>
                {
                    p.Incident = TaskAPI.Incident;

                }
                );
            }

            //退出
            if (IsSend)
            {
                Exit();
            }
            return true;
        }
        #endregion

        #region Event Page
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InitControls();
            }
        }
        #endregion

        #region Event Kcry(考察人员)
        protected void Kcry_TextChanged(object sender, EventArgs e)
        {
            //string SQL         = string.Format("select rtrim(UserShortName) as username, rtrim(UserFullName) AS fullname from Ult_UserJob where rtrim(UserShortName)='" + ((Anthem.DialogExt)sender).Text + "'");
            //DataTable dt       = ORM.Context2.ExecuteDataSet(new Command(SQL)).Tables[0];
            //string strName     = dt.Rows.Count > 0 ? dt.Rows[0][0].ToString() : "";
            //string strFullName = dt.Rows.Count > 0 ? dt.Rows[0][1].ToString() : "";

            //switch ((sender as DialogExt).ID)
            //{
            //    case "Kcry":
            //        GetUserName.Text += "," + strFullName;
            //        GetUserName.Text = GetUserName.Text.Trim(',');
            //        Kcry.Text = GetUserName.Text;
            //        KcryUser.Text += "," + "xckg/"+ strName;
            //        KcryUser.Text = KcryUser.Text.Trim(',');
            //        break;
            //}

            string user = "'" + Kcry.Text.Replace(",", "','") + "-999'";//string.Format("'{0}'", ConferTo.Text.Replace("'", "''"));
            Kcry.Attributes["UserName"] = user;
            string users = user;

            string[] arrValue = user.Replace("'", "").Split(',');
            string sql = string.Format("select distinct UserShortName as UserName, UserFullName from Ult_UserJob where UserShortName <>'' and UserShortName in({0})", string.IsNullOrEmpty(users) ? "'-999'" : users);
            DataTable dt = ORM.Context2.ExecuteDataSet(new Command(sql)).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                string tmp = "";
                Kcry.Text = "";
                //foreach (DataRow dr in dt.Rows)
                //{
                //    Participants.Text += (string.IsNullOrEmpty(Participants.Text) ? "" : "; ") + dr["UserFullName"].ToString();
                //    tmp += (string.IsNullOrEmpty(tmp) ? "" : ",") + "'" + dr["UserName"].ToString() + "'";
                //}

                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < arrValue.Length; i++)
                    {
                        if (arrValue[i] == dr["UserName"].ToString())
                        {
                            arrValue[i] = string.Format("{0}:{1}", arrValue[i], dr["UserFullName"].ToString());
                            break;
                        }
                    }
                }

                for (int i = 0; i < arrValue.Length; i++)
                {
                    if (arrValue[i].Contains(":"))
                    {
                        string[] s = arrValue[i].Split(':');
                        Kcry.Text += (string.IsNullOrEmpty(Kcry.Text) ? "" : "; ") + s[1];
                        tmp += (string.IsNullOrEmpty(tmp) ? "" : ",") + "'" + s[0] + "'";
                    }
                }

                Kcry.Attributes["UserName"] = tmp;
                KcryUser.Text = tmp.Replace("'", "") + (string.IsNullOrEmpty(tmp) ? "" : ",");
                Kcry.Attributes["onclick"] = string.Format("OpenDialog2('../../Workflow/spMulEmployee.aspx?v=1&ep={0}','840','560','v',this.id,'1')", KcryUser.Text.Replace(";", ","));
            }
            else
            {
                Kcry.Text = "";
                Kcry.Attributes["UserName"] = "";
                KcryUser.Text = "";
            }
        }
        #endregion

        #region Event Clear
        protected void Clear_Click(object sender, EventArgs e)
        {
            Kcry.Text = "";
            KcryUser.Text = "";
        }
        #endregion

        #region Event Button Click

        #region Event Save As Draft
        protected void SaveAsDraft_Click(object sender, EventArgs e)
        {
            bool success = Submit(false);
            Anthem.Manager.AddScriptForClientSideEval(string.Format("JSInfomation('{0}')", success ? "保存成功!" : "保存失败!"));
        }
        #endregion

        #region Event Send
        protected void Send_Click(object sender, EventArgs e)
        {
            List<string> msg = DataValidation();
            if (msg.Count > 0)
            {
                Anthem.Manager.AddScriptForClientSideEval(Alert(msg));
                return;
            }

            bool success = Submit(true);
            (sender as spWeb.Controls.AssessmentExt).Refresh();
            Anthem.Manager.AddScriptForClientSideEval(string.Format("JSInfomation('{0}');{1}", success ? "提交成功!" : "提交失败!", success ? "window.close();" : ""));
        }
        #endregion

        #region Event Aborted
        protected void Aborted_Click(object sender, EventArgs e)
        {
            (dc_xz_Flswsqd.process == TaskAPI.Process & dc_xz_Flswsqd.incident == TaskAPI.Incident).Edit<dc_xz_Flswsqd>(p => { p.Status = 4; });
        }
        #endregion

        #endregion

        #region Event City(城市公司) & Gsgs(开发公司)
        protected void City_TextChanged(object sender, EventArgs e)
        {
            db.BindGsgs(Gsgs, City.SelectedValue);
        }
        protected void Gsgsbmkfgs_TextChanged(object sender, EventArgs e)
        {
            db.BindXmmc(Xmmc, Gsgs.SelectedValue);
        }
        #endregion
    }
}